// pages/report/index.js
const { fetchReportList, getReportDownload } = require('../../api/api.js')
const { requestUrlDomain } = require('../../utils/request.js')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    search: '',
    list: [],
    baseConfig: {
      isAutoTriggered: false,
      shake: false, // 是否开启下拉震动
      height: 70, // 下拉高度
      text: {
        color: '#aaaaaa', // 文字颜色
        shadow: 5, // 是否开启shadow阴影,0为不开启,数值越大阴影范围越大
      },
    },
  },
  addNewReport() {
    wx.navigateTo({
      url: '/pages/checkReport/index',
    })
  },
  async getReportList() {
    const inspector = wx.getStorageSync('inspector-info')
    const { token: Authorization } = JSON.parse(inspector)
    const res = await fetchReportList({
      key: this.data.search,
      current: 1,
      size: 9999,
    }, {
      header: {
        Authorization
      },
    })
    this.setData({
      list: res.data.records
    })
    const scroller = this.selectComponent('.elm-scroller');
    scroller.settriggered(false)
  },
  handleSearchInput(e) {
    const search = e.detail;
    this.setData({
      search
    })
    clearTimeout(this.timer);
    this.timer = setTimeout(() => {
      this.getReportList();
    }, 500)
  },
  async handleDownloadReport(e) {
    const inspector = wx.getStorageSync('inspector-info')
    const { token: Authorization } = JSON.parse(inspector)
    const { id } = e.currentTarget.dataset;
    wx.showLoading({ title: "下载中..." });
    wx.downloadFile({
      url: `${requestUrlDomain}/system/report/download/${id}`,
      header: {
        Authorization
      },
      success: (res) => {
        if (res.tempFilePath) {
          wx.openDocument({
            filePath: res.tempFilePath,
            fileType: 'pdf',
            fail: (err) => {
              console.error(err);
            },
            complete: () => {
              wx.hideLoading();
            }
          })
        }
      },
      fail: (err) => {
        console.error(err);
        wx.hideLoading();
      }
    })
  },
  goReportDetail(e) {
    const { index } = e.currentTarget.dataset
    const data = this.data.list[index]
    wx.setStorageSync('reportDetail', JSON.stringify(data))
    wx.navigateTo({
      url: `/pages/checkReport/index?id=${data.id}`,
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.getReportList();
    wx.removeStorageSync('reportDetail')
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})